<template>
  <div class="project-docs">
    <div class="docs-header">
      <div class="header-left">
        <el-button @click="$router.back()" :icon="ArrowLeft" circle />
        <h1>项目文档管理</h1>
        <span class="project-name">{{ project?.name }}</span>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新建文档
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyWord"
              placeholder="搜索文档标题或内容..."
              style="width: 300px;"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="标签">
            <el-select
              v-model="searchForm.tip"
              placeholder="选择标签"
              style="width: 200px;"
              clearable
              filterable
              allow-create
            >
              <el-option
                v-for="tag in availableTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px;"
            />
          </el-form-item>
          
          <el-form-item label="共享状态">
            <el-select
              v-model="searchForm.isShare"
              placeholder="选择状态"
              style="width: 120px;"
              clearable
            >
              <el-option label="全部" :value="undefined" />
              <el-option label="已共享" :value="true" />
              <el-option label="未共享" :value="false" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 文档列表 -->
    <el-card class="docs-list-card">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="docs.length === 0" class="empty-state">
        <el-empty description="暂无文档">
          <el-button type="primary" @click="showCreateDialog = true">
            创建第一个文档
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="docs-grid">
        <div
          v-for="doc in docs"
          :key="doc.id"
          class="doc-card"
          @click="viewDoc(doc)"
        >
          <div class="doc-header">
            <div class="doc-title">{{ doc.title }}</div>
            <div class="doc-actions" @click.stop>
              <el-dropdown @command="handleDocAction">
                <el-button type="text" size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'edit', doc }">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'share', doc }">
                      <el-icon><Share /></el-icon>
                      {{ doc.isShare ? '取消共享' : '设为共享' }}
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'delete', doc }" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="doc-content">
            <div class="doc-preview" v-html="getDocPreview(doc.content)"></div>
          </div>
          
          <div class="doc-footer">
            <div class="doc-meta">
              <span class="doc-date">
                <el-icon><Calendar /></el-icon>
                {{ formatDate(doc.createdAt) }}
              </span>
              <span class="doc-author">
                <el-icon><User /></el-icon>
                {{ doc.createByName }}
              </span>
              <span v-if="doc.isShare" class="share-badge">
                <el-icon><Share /></el-icon>
                已共享
              </span>
            </div>
            <div v-if="doc.tips" class="doc-tags">
              <el-tag
                v-for="tag in getDocTags(doc.tips)"
                :key="tag"
                size="small"
                type="info"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          :current-page="pagination.pageNumber"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑文档对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingDoc ? '编辑文档' : '新建文档'"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="文档标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文档标题" />
        </el-form-item>
        
        <el-form-item label="标签" prop="tips">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            placeholder="选择或创建标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文档内容" prop="content">
          <div class="rich-editor">
            <div ref="editorRef" style="height: 400px;"></div>
          </div>
        </el-form-item>
        
        <el-form-item label="共享设置">
          <el-switch
            v-model="form.isShare"
            active-text="共享给项目成员"
            inactive-text="仅自己可见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 文档查看对话框 -->
    <el-dialog
      v-model="showViewDialog"
      :title="viewingDoc?.title"
      width="900px"
      @close="viewingDoc = null"
    >
      <div v-if="viewingDoc" class="doc-viewer">
        <div class="doc-header">
        <div class="doc-meta">
          <span class="doc-date">
            <el-icon><Calendar /></el-icon>
            创建时间：{{ formatDate(viewingDoc.createdAt) }}
          </span>
          <span class="doc-author">
            <el-icon><User /></el-icon>
            创建人：{{ viewingDoc.createByName }}
          </span>
          <span v-if="viewingDoc.isShare" class="share-badge">
            <el-icon><Share /></el-icon>
            已共享
          </span>
        </div>
          <div v-if="viewingDoc.tips" class="doc-tags">
            <el-tag
              v-for="tag in getDocTags(viewingDoc.tips)"
              :key="tag"
              size="small"
              type="info"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div class="doc-content" v-html="viewingDoc.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft, Plus, Search, Refresh, MoreFilled, Edit, Share, Delete, Calendar, User } from '@element-plus/icons-vue'
import { getProjectList, type Project } from '@/api/project'
import { 
  getProjectDocList, 
  createProjectDoc, 
  updateProjectDoc, 
  deleteProjectDoc, 
  getProjectDocTips,
  type ProjectDoc, 
  type CreateProjectDocRequest, 
  type UpdateProjectDocRequest,
  type ProjectDocListParams 
} from '@/api/projectDoc'
import dayjs from 'dayjs'

const route = useRoute()
const projectId = computed(() => parseInt(route.params.id as string))

const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const showViewDialog = ref(false)

const project = ref<Project | null>(null)
const docs = ref<ProjectDoc[]>([])
const availableTags = ref<string[]>([])
const editingDoc = ref<ProjectDoc | null>(null)
const viewingDoc = ref<ProjectDoc | null>(null)
const editorRef = ref()

const searchForm = reactive({
  keyWord: '',
  tip: '',
  dateRange: [] as string[],
  isShare: undefined as boolean | undefined
})

const pagination = reactive({
  pageNumber: 1,
  pageSize: 20
})

const total = ref(0)

const formRef = ref<FormInstance>()
const form = reactive({
  title: '',
  content: '',
  tags: [] as string[],
  isShare: false
})

const rules: FormRules = {
  title: [
    { required: true, message: '请输入文档标题', trigger: 'blur' },
    { max: 100, message: '文档标题不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文档内容', trigger: 'blur' }
  ]
}

const fetchProject = async () => {
  try {
    const result = await getProjectList({
      pageDto: { pageNumber: 1, pageSize: 1 }
    })
    const foundProject = result.data.items.find(p => p.id === projectId.value)
    if (foundProject) {
      project.value = foundProject
    }
  } catch (error) {
    ElMessage.error('获取项目信息失败')
  }
}

const fetchDocs = async () => {
  loading.value = true
  try {
    const params: ProjectDocListParams = {
      projectId: projectId.value,
      keyWord: searchForm.keyWord || undefined,
      tip: searchForm.tip || undefined,
      isShare: searchForm.isShare,
      pageDto: {
        pageNumber: pagination.pageNumber,
        pageSize: pagination.pageSize
      }
    }
    
    // 添加时间范围筛选
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      // 这里需要在后端API中添加时间范围支持
      // 暂时在前端进行筛选
    }
    
    const result = await getProjectDocList(params)
    docs.value = result.data.items
    total.value = result.data.totalCount
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

const fetchTags = async () => {
  try {
    const result = await getProjectDocTips(projectId.value)
    availableTags.value = result.data || []
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

const handleSearch = () => {
  pagination.pageNumber = 1
  fetchDocs()
}

const handleReset = () => {
  searchForm.keyWord = ''
  searchForm.tip = ''
  searchForm.dateRange = []
  searchForm.isShare = undefined
  pagination.pageNumber = 1
  fetchDocs()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNumber = 1
  fetchDocs()
}

const handleCurrentChange = (page: number) => {
  pagination.pageNumber = page
  fetchDocs()
}

const viewDoc = (doc: ProjectDoc) => {
  viewingDoc.value = doc
  showViewDialog.value = true
}

const handleDocAction = async (command: { action: string; doc: ProjectDoc }) => {
  const { action, doc } = command
  
  switch (action) {
    case 'edit':
      editDoc(doc)
      break
    case 'share':
      toggleShare(doc)
      break
    case 'delete':
      deleteDoc(doc)
      break
  }
}

const editDoc = (doc: ProjectDoc) => {
  editingDoc.value = doc
  form.title = doc.title
  form.content = doc.content
  form.tags = getDocTags(doc.tips)
  form.isShare = doc.isShare
  showCreateDialog.value = true
}

const toggleShare = async (doc: ProjectDoc) => {
  try {
    const updateData: UpdateProjectDocRequest = {
      id: doc.id,
      title: doc.title,
      content: doc.content,
      tips: doc.tips,
      isShare: !doc.isShare
    }
    await updateProjectDoc(updateData)
    ElMessage.success(doc.isShare ? '已取消共享' : '已设为共享')
    fetchDocs()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteDoc = async (doc: ProjectDoc) => {
  try {
    await ElMessageBox.confirm('确定要删除这个文档吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteProjectDoc(doc.id)
    ElMessage.success('删除成功')
    fetchDocs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetForm = () => {
  editingDoc.value = null
  form.title = ''
  form.content = ''
  form.tags = []
  form.isShare = false
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    if (editingDoc.value) {
      const updateData: UpdateProjectDocRequest = {
        id: editingDoc.value.id,
        title: form.title,
        content: form.content,
        tips: form.tags.join(','),
        isShare: form.isShare
      }
      await updateProjectDoc(updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateProjectDocRequest = {
        projectId: projectId.value,
        title: form.title,
        content: form.content,
        tips: form.tags.join(','),
        isShare: form.isShare
      }
      await createProjectDoc(createData)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    fetchDocs()
    fetchTags() // 刷新标签列表
  } catch (error) {
    ElMessage.error(editingDoc.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const getDocPreview = (content: string) => {
  if (!content) return '暂无内容'
  // 移除HTML标签并截取前100个字符
  const text = content.replace(/<[^>]*>/g, '')
  return text.length > 100 ? text.substring(0, 100) + '...' : text
}

const getDocTags = (tips: string) => {
  if (!tips) return []
  return tips.split(',').map(tag => tag.trim()).filter(tag => tag)
}

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

onMounted(() => {
  fetchProject()
  fetchDocs()
  fetchTags()
})
</script>

<style scoped lang="scss">
.project-docs {
  padding: 24px;
  
  .docs-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      h1 {
        font-size: 24px;
        color: #333;
        margin: 0;
      }
      
      .project-name {
        color: #666;
        font-size: 14px;
        background: #f0f2f5;
        padding: 4px 12px;
        border-radius: 12px;
      }
    }
  }
  
  .search-card {
    margin-bottom: 24px;
    
    .search-form {
      .el-form {
        margin-bottom: 0;
      }
    }
  }
  
  .docs-list-card {
    .loading-container {
      padding: 40px 0;
    }
    
    .empty-state {
      padding: 60px 0;
    }
    
    .docs-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 20px;
      margin-bottom: 24px;
      
      .doc-card {
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        padding: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #fff;
        
        &:hover {
          border-color: #409eff;
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
          transform: translateY(-2px);
        }
        
        .doc-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 12px;
          
          .doc-title {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            flex: 1;
            margin-right: 12px;
            line-height: 1.4;
          }
          
          .doc-actions {
            opacity: 0;
            transition: opacity 0.3s ease;
          }
        }
        
        &:hover .doc-actions {
          opacity: 1;
        }
        
        .doc-content {
          margin-bottom: 16px;
          
          .doc-preview {
            color: #666;
            font-size: 14px;
            line-height: 1.6;
            max-height: 60px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            line-clamp: 3;
            -webkit-box-orient: vertical;
          }
        }
        
        .doc-footer {
          .doc-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;
            
            .doc-date {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #999;
              font-size: 12px;
            }
            
            .doc-author {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #999;
              font-size: 12px;
            }
            
            .share-badge {
              display: flex;
              align-items: center;
              gap: 4px;
              color: #67c23a;
              font-size: 12px;
              background: #f0f9ff;
              padding: 2px 8px;
              border-radius: 12px;
            }
          }
          
          .doc-tags {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
            
            .tag-item {
              font-size: 11px;
            }
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

.rich-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  
  .ql-toolbar {
    border-bottom: 1px solid #dcdfe6;
  }
  
  .ql-container {
    border: none;
  }
}

.doc-viewer {
  .doc-header {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
    
    .doc-meta {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 12px;
      
      .doc-date {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #666;
        font-size: 14px;
      }
      
      .doc-author {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #666;
        font-size: 14px;
      }
      
      .share-badge {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #67c23a;
        font-size: 14px;
        background: #f0f9ff;
        padding: 4px 12px;
        border-radius: 16px;
      }
    }
    
    .doc-tags {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      
      .tag-item {
        font-size: 12px;
      }
    }
  }
  
  .doc-content {
    padding: 20px;
    background: #fafafa;
    border-radius: 8px;
    min-height: 200px;
    
    h1, h2, h3, h4, h5, h6 {
      margin-top: 0;
      margin-bottom: 16px;
      color: #333;
    }
    
    p {
      margin-bottom: 12px;
      line-height: 1.6;
      color: #555;
    }
    
    ul, ol {
      margin-bottom: 12px;
      padding-left: 20px;
    }
    
    li {
      margin-bottom: 4px;
    }
    
    blockquote {
      margin: 16px 0;
      padding: 12px 16px;
      background: #f8f9fa;
      border-left: 4px solid #409eff;
      border-radius: 0 4px 4px 0;
    }
    
    code {
      background: #f1f2f3;
      padding: 2px 6px;
      border-radius: 3px;
      font-family: 'Courier New', monospace;
      font-size: 13px;
    }
    
    pre {
      background: #f8f9fa;
      padding: 16px;
      border-radius: 6px;
      overflow-x: auto;
      margin: 16px 0;
      
      code {
        background: none;
        padding: 0;
      }
    }
  }
}

@media (max-width: 768px) {
  .project-docs {
    padding: 16px;
    
    .docs-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .header-left {
        h1 {
          font-size: 20px;
        }
      }
    }
    
    .search-card {
      .search-form {
        .el-form {
          .el-form-item {
            margin-bottom: 12px;
          }
        }
      }
    }
    
    .docs-list-card {
      .docs-grid {
        grid-template-columns: 1fr;
        gap: 16px;
        
        .doc-card {
          padding: 16px;
          
          .doc-header {
            .doc-title {
              font-size: 15px;
            }
          }
          
          .doc-content {
            .doc-preview {
              font-size: 13px;
            }
          }
        }
      }
    }
  }
}
</style>
